import { defineStore } from 'pinia';
import { ref, computed, nextTick } from 'vue';
import { cloneDeep } from 'lodash-es'; // 引入 cloneDeep
import { v4 as uuidv4 } from 'uuid'; // 确保 uuid 已导入
import { getComponentConfig, type PropertyConfig } from '../config/propertyPanelConfig'; // <--- 导入配置
import type { CSSProperties } from 'vue'; // 引入 CSSProperties 类型

// 定义画布组件的接口 (与 CanvasArea 一致)
export interface CanvasComponent {
    id: string;
    type: string;
    props: Record<string, any>;
    style: Record<string, any>;
    events?: Record<string, string>; // 添加可选的 events 属性
    children?: CanvasComponent[];
    name?: string; // 可选的组件名称
    visible?: boolean; // 可选的可见性标志
}

// **导出 ComponentInfo**
export interface ComponentInfo {
    id: string;
    name?: string;
    type: string;
    depth: number;
    visible?: boolean;
}

const MAX_HISTORY_LENGTH = 50; // 限制历史记录数量

export const useDesignStore = defineStore('design', () => {
    // State
    const canvasComponents = ref<CanvasComponent[]>([]);
    const selectedComponentId = ref<string | null>(null);
    const undoStack = ref<CanvasComponent[][]>([]); // 撤销栈
    const redoStack = ref<CanvasComponent[][]>([]); // 重做栈
    const isRestoringState = ref(false); // 使用 ref 使其可在 action 内部修改和访问
    const currentMaxZIndex = ref(0); // 新增 state: 用于追踪当前最大 zIndex
    const gridSize = ref(5); // <-- 添加 gridSize state，初始值为 5
    const isDraggingComponent = ref(false); // ++ Re-add dragging state ++
    // 添加画布尺寸状态
    const canvasSize = ref({ width: 600, height: 400 }); // 默认尺寸
    // 新增组件复制粘贴的剪贴板状态
    const clipboardComponent = ref<CanvasComponent | null>(null);

    // --- 内部辅助函数 ---
    // **重新添加 findComponentById**
    const findComponentById = (components: CanvasComponent[], id: string): CanvasComponent | null => {
        for (const component of components) {
            if (component.id === id) {
                return component;
            }
            if (component.children) {
                const foundInChildren = findComponentById(component.children, id);
                if (foundInChildren) {
                    return foundInChildren;
                }
            }
        }
        return null;
    };

    // **重新添加 findParentComponent**
    const findParentComponent = (components: CanvasComponent[], id: string): CanvasComponent | null => {
        for (const component of components) {
            if (component.children?.some(child => child.id === id)) {
                return component; // 当前组件是父组件
            }
            if (component.children) {
                const parent = findParentComponent(component.children, id);
                if (parent) {
                    return parent; // 在子树中找到父组件
                }
            }
        }
        return null;
    };

    // Getters (Computed)
    const selectedComponent = computed(() => {
        if (!selectedComponentId.value) return null;
        // 使用重新添加的 findComponentById
        return findComponentById(canvasComponents.value, selectedComponentId.value);
    });

    // **Getter 使用外部定义的 ComponentInfo**
    const allComponentsFlatList = computed((): ComponentInfo[] => {
        const result: ComponentInfo[] = [];
        const traverse = (components: CanvasComponent[], depth: number) => {
            components.forEach(comp => {
                result.push({
                    id: comp.id,
                    name: comp.name,
                    type: comp.type,
                    depth: depth,
                    visible: comp.visible !== false
                });
                if (comp.children && comp.children.length > 0) {
                    traverse(comp.children, depth + 1);
                }
            });
        };
        traverse(canvasComponents.value, 0);
        return result;
    });

    const canUndo = computed(() => undoStack.value.length > 0);
    const canRedo = computed(() => redoStack.value.length > 0);

    // --- 私有辅助函数：记录历史 --- 
    const recordHistory = () => {
        if (isRestoringState.value) return; // 如果是撤销/重做操作，则不记录
        // console.log('记录历史状态...');
        const snapshot = cloneDeep(canvasComponents.value);
        undoStack.value.push(snapshot);
        if (undoStack.value.length > MAX_HISTORY_LENGTH) {
            undoStack.value.shift(); // 移除最旧的记录
        }
        redoStack.value = [];
        // console.log('历史记录已添加，撤销栈大小:', undoStack.value.length);
    };

    // --- 内部辅助函数：查找并更新最大 zIndex ---
    const findAndUpdateMaxZIndex = (components: CanvasComponent[]) => {
        let maxZ = currentMaxZIndex.value; // 从当前值开始
        const traverse = (comps: CanvasComponent[]) => {
            comps.forEach(comp => {
                const z = parseInt(String(comp.style?.zIndex), 10);
                if (!isNaN(z) && z > maxZ) {
                    maxZ = z;
                }
                if (comp.children) {
                    traverse(comp.children);
                }
            });
        };
        traverse(components);
        // 如果找到更大的 zIndex，更新 store 中的状态
        if (maxZ > currentMaxZIndex.value) {
            currentMaxZIndex.value = maxZ;
        }
        // console.log('Updated max zIndex:', currentMaxZIndex.value);
    };

    // --- 新增：内部辅助函数：查找最小 zIndex --- 
    const findMinZIndex = (components: CanvasComponent[]): number => {
        let minZ = 0; // 默认最小为 0，如果所有 zIndex 都 > 0
        let foundAny = false;
        const traverse = (comps: CanvasComponent[]) => {
            comps.forEach(comp => {
                if (comp.style?.zIndex !== undefined) {
                    const z = parseInt(String(comp.style.zIndex), 10);
                    if (!isNaN(z)) {
                        if (!foundAny || z < minZ) {
                            minZ = z;
                            foundAny = true;
                        }
                    }
                }
                if (comp.children) {
                    traverse(comp.children);
                }
            });
        };
        traverse(components);
        // console.log('[Store findMinZIndex] Found min zIndex:', minZ);
        return minZ;
    };

    // Actions (Methods)
    const addComponent = (component: CanvasComponent, parentId: string | null = null) => {
        // ++ Log received parentId ++
        console.log(`[Store AddComponent] Received parentId:`, parentId, `(Type: ${typeof parentId})`); 
        
        recordHistory();
        // 为新组件设置默认可见性和初始 zIndex
        const initialZIndex = currentMaxZIndex.value + 1;
        const componentConfig = getComponentConfig(component.type); // 获取配置

        const componentToAdd: CanvasComponent = {
            ...cloneDeep(component), // 深拷贝传入的组件基础信息
            id: component.id || `${component.type}-${uuidv4().substring(0, 8)}`, // 确保有 ID
            visible: component.visible !== false, // 默认可见
            props: { ...(component.props || {}) }, // 初始化 props
            style: {
                ...(component.style || {}), // 保留传入的样式（如拖放时的 left/top）
                zIndex: initialZIndex // 设置初始 zIndex
            }
        };

        // 应用配置中的默认值
        componentConfig.forEach((config: PropertyConfig) => {
            if (config.defaultValue !== undefined) {
                switch (config.category) {
                    case 'style':
                        // 仅当原始 style 中没有该 key 时才应用默认值
                        if (!(componentToAdd.style && componentToAdd.style.hasOwnProperty(config.key))) {
                            if (!componentToAdd.style) componentToAdd.style = {}; // 确保 style 对象存在
                            componentToAdd.style[config.key] = cloneDeep(config.defaultValue);
                        }
                        break;
                    case 'props':
                        // 仅当原始 props 中没有该 key 时才应用默认值
                        if (!(componentToAdd.props && componentToAdd.props.hasOwnProperty(config.key))) {
                            if (!componentToAdd.props) componentToAdd.props = {}; // 确保 props 对象存在
                            componentToAdd.props[config.key] = cloneDeep(config.defaultValue);
                        }
                        break;
                    case 'root':
                        // 仅当原始 component 中没有该 key 时才应用默认值 (处理 name, visible 等)
                        if (!(componentToAdd.hasOwnProperty(config.key))) {
                            (componentToAdd as any)[config.key] = cloneDeep(config.defaultValue);
                        }
                        break;
                }
            }
        });
        
        // 确保宽度和高度属性始终存在，这对于调整框显示很重要
        if (!componentToAdd.style.width) {
            componentToAdd.style.width = '100px'; // 默认宽度
        }
        
        if (!componentToAdd.style.height) {
            componentToAdd.style.height = '32px'; // 默认高度
        }
        
        // --- 设置特定组件的默认字体颜色 ---
        if (componentToAdd.type === 'span') { // 仅针对 span 类型
            if (!componentToAdd.style) {
                componentToAdd.style = {}; // 确保 style 对象存在
            }
            // 只有当 color 属性不存在或为空时才设置默认值
            if (!componentToAdd.style.color) {
                componentToAdd.style.color = '#606266'; // 设置为 Element Plus 的主要文本颜色
                console.log(`[Store AddComponent] Set default color for span ${componentToAdd.id}`);
            }
        }
        // --- 默认颜色设置结束 ---

        // ++ Add default children based on config
        const configWithOptions = componentConfig.find(c => c.key === 'children' && c.hasOptions && c.defaultChildren);
        if (configWithOptions && configWithOptions.defaultChildren && componentToAdd.children?.length === 0) { // Only add if no children were provided initially
            console.log(`[Store AddComponent] Adding default children for ${componentToAdd.type}`);
            componentToAdd.children = configWithOptions.defaultChildren.map(childConfig => ({
                // Create a full CanvasComponent structure for each child
                id: `${childConfig.type}-${uuidv4().substring(0, 8)}`,
                type: childConfig.type,
                props: { ...(childConfig.props || {}) },
                style: { position: 'relative' }, // Default style for children in groups
                // children: [] // Assuming default options don't have nested children
            }));
        }
        // --- 默认子项添加结束 ---

        // 记录组件添加后的状态，特别是宽度和高度
        console.log(`[Store AddComponent] Component ${componentToAdd.id} final style:`, {
            width: componentToAdd.style.width,
            height: componentToAdd.style.height,
            left: componentToAdd.style.left,
            top: componentToAdd.style.top
        });

        currentMaxZIndex.value = initialZIndex; // 更新最大 zIndex

        // --- 定位逻辑调整 --- 
        if (parentId) {
            const parent = findComponentById(canvasComponents.value, parentId);
            console.log(`[Store AddComponent] Attempting to add to parent. Found parent component for ID ${parentId}:`, parent ? parent.id : 'Not Found');
            
            if (parent && isContainerType(parent.type)) {
                // 确保父容器有定位上下文 (如果需要)
                if (!parent.style) parent.style = {};
                if (!parent.style.position) {
                    parent.style.position = 'relative'; 
                    console.log(`[Store AddComponent] Set parent ${parent.id} position to relative.`);
                }

                // **直接使用传入的 style 作为相对位置**
                // (假设调用者已计算好相对坐标)
                if (!componentToAdd.style) componentToAdd.style = {}; // 确保 style 存在
                componentToAdd.style.position = 'absolute'; 
                // left 和 top 应由调用者在 component.style 中提供
                console.log(`[Store AddComponent] Applying provided relative style for child ${componentToAdd.id}:`, componentToAdd.style);

                // 添加到父组件
                if (!parent.children) parent.children = [];
                parent.children.push(componentToAdd);
                console.log(`组件 ${componentToAdd.id} (z:${componentToAdd.style?.zIndex}) 已添加到父组件 ${parentId} 中 (Using Relative Pos)`);

                // ++ 移除 nextTick 强制更新 ++ 
                // nextTick(() => { ... });

            } else {
                // Fallback to root
                console.warn(`[Store AddComponent] Failed to add to parent ${parentId}. Reason: ${parent ? 'Parent is not a container type ('+parent.type+')' : 'Parent not found'}. Adding to root instead.`);
                componentToAdd.style.position = 'absolute';
                canvasComponents.value.push(componentToAdd);
                console.log(`组件 ${componentToAdd.id} (z:${componentToAdd.style?.zIndex}) 已添加到根画布 [Fallback]`);
            }
        } else {
            // 添加到根画布 (保持不变，需要绝对定位)
            console.log(`[Store AddComponent] Adding component ${componentToAdd.id} to root.`);
            componentToAdd.style.position = 'absolute'; 
            canvasComponents.value.push(componentToAdd);
            console.log(`组件 ${componentToAdd.id} (z:${componentToAdd.style?.zIndex}) 已添加到根画布 (Absolute Pos)`);
        }
        // --- 定位逻辑结束 ---

        // 更新最大 zIndex
        const newZ = parseInt(String(componentToAdd.style?.zIndex), 10);
        if (!isNaN(newZ) && newZ > currentMaxZIndex.value) {
            currentMaxZIndex.value = newZ;
        }
    };

    const selectComponent = (id: string | null) => {
        // 选中操作通常不记录历史，除非需要撤销选中？暂时不记
        console.log(`Store: selectComponent action 触发，ID: ${id}`);
        selectedComponentId.value = id;
    };

    // deleteComponent 需要递归查找并删除 (内部也可能间接依赖 findComponentById)
    const deleteComponentRecursive = (components: CanvasComponent[], id: string): boolean => {
        const index = components.findIndex(c => c.id === id);
        if (index !== -1) {
            components.splice(index, 1);
            return true; // 找到并删除
        }
        for (const component of components) {
            if (component.children) {
                if (deleteComponentRecursive(component.children, id)) {
                    return true; // 在子组件中找到并删除
                }
            }
        }
        return false; // 未找到
    };
    const deleteComponent = (id: string) => {
        recordHistory();
        if (deleteComponentRecursive(canvasComponents.value, id)) {
            if (selectedComponentId.value === id) {
                selectedComponentId.value = null;
            }
            console.log(`组件 ${id} 已被删除`);
        } else {
            console.warn(`删除组件失败：未找到 ID 为 ${id} 的组件`);
        }
    };

    // updateComponentStyle 需要 findComponentById 和 findParentComponent
    const updateComponentStyle = (id: string, newStyle: Partial<CanvasComponent['style']>) => {
        const component = findComponentById(canvasComponents.value, id);
        if (!component) {
            console.warn(`[Store UpdateStyle] Component ${id} not found.`); // ++ LOG
            return;
        }
        if (!component.style) { component.style = {}; }

        console.log(`[Store UpdateStyle] Updating ${id} with style:`, JSON.stringify(newStyle)); // ++ LOG
        recordHistory();

        // --- 特殊处理：确保宽度和高度被正确处理 ---
        // 使用临时变量保存要应用的样式更改
        const styleUpdates: Record<string, any> = {};
        let hasChanges = false;
        
        for (const key in newStyle) {
            if (Object.prototype.hasOwnProperty.call(newStyle, key)) {
                const oldValue = component.style[key];
                const newValue = newStyle[key as keyof CanvasComponent['style']];
                
                // 确保值有效 - 特别是宽度和高度
                if (key === 'width' || key === 'height') {
                    // 检查新值是否有效
                    if (typeof newValue === 'number') {
                        styleUpdates[key] = `${newValue}px`; // 转换为像素字符串
                        hasChanges = true;
                    } else if (typeof newValue === 'string' && newValue.trim() !== '') {
                        styleUpdates[key] = newValue;
                        hasChanges = true;
                    } else {
                        console.warn(`[Store UpdateStyle] Ignoring invalid ${key} value: ${newValue}`);
                    }
                } else {
                    // 其他样式属性直接更新
                    styleUpdates[key] = newValue;
                    hasChanges = true;
                }
            }
        }
        
        // 应用有效的样式更改
        if (hasChanges) {
            for (const key in styleUpdates) {
                component.style[key] = styleUpdates[key];
            }
            console.log(`[Store UpdateStyle] Style after update for ${id}:`, 
                JSON.stringify({
                    width: component.style.width,
                    height: component.style.height,
                    left: component.style.left,
                    top: component.style.top
                })
            );
        } else {
            console.warn(`[Store UpdateStyle] No valid style changes to apply for ${id}`);
        }
        // --- 更新结束 ---

        // 检查 zIndex
        if ('zIndex' in newStyle) {
            const newZ = parseInt(String(component.style.zIndex), 10);
            console.log(`[Store UpdateStyle] zIndex changed for ${id}. New value: ${newZ}. Current max: ${currentMaxZIndex.value}`); // ++ LOG
            if (!isNaN(newZ) && newZ > currentMaxZIndex.value) {
                currentMaxZIndex.value = newZ;
                console.log(`[Store UpdateStyle] Updated currentMaxZIndex to: ${currentMaxZIndex.value}`); // ++ LOG
            }
        }
    };

    // updateComponentProps 需要 findComponentById
    const updateComponentProps = (id: string, newProps: Partial<CanvasComponent['props']>) => {
        // 使用重新添加的 findComponentById
        const component = findComponentById(canvasComponents.value, id);
        if (component) {
            recordHistory(); // 在 Action 内部记录
            component.props = { ...component.props, ...newProps };
        } else {
            console.warn(`更新 Props 失败：未找到 ID 为 ${id} 的组件`);
        }
    };

    // **新增 Action: 更新组件根属性**
    const updateComponentRootProps = (id: string, newRootProps: { name?: string; visible?: boolean }) => {
        const component = findComponentById(canvasComponents.value, id);
        if (!component) {
            console.warn(`更新根属性失败：未找到 ID 为 ${id} 的组件`);
            return;
        }
        recordHistory();
        let changed = false;
        if (newRootProps.name !== undefined && component.name !== newRootProps.name) {
            component.name = newRootProps.name;
            changed = true;
        }
        if (newRootProps.visible !== undefined && component.visible !== newRootProps.visible) {
            component.visible = newRootProps.visible;
            changed = true;
        }
        if (changed) {
            console.log(`组件 ${id} 的根属性已更新:`, newRootProps);
        } else {
            console.log(`组件 ${id} 的根属性无需更新。`);
            // 如果没有实际变化，可以考虑不推入历史记录，但目前 recordHistory 在开头调用了
        }
    };

    // --- 新增：层级调整 Actions ---
    const bringToFront = (id: string) => {
        console.log(`[Store BringToFront] Action called for ${id}`); // ++ LOG
        const component = findComponentById(canvasComponents.value, id);
        if (!component) {
            console.warn(`[Store BringToFront] Component ${id} not found.`); // ++ LOG
            return;
        }

        // 找到当前的全局最大 zIndex (确保最新)
        console.log(`[Store BringToFront] Finding max zIndex before bringing ${id} to front...`); // ++ LOG
        findAndUpdateMaxZIndex(canvasComponents.value);
        console.log(`[Store BringToFront] Current max zIndex is: ${currentMaxZIndex.value}`); // ++ LOG

        const newZIndex = currentMaxZIndex.value + 1;
        console.log(`[Store BringToFront] Calculated new zIndex for ${id}: ${newZIndex}`); // ++ LOG
        updateComponentStyle(id, { zIndex: newZIndex });
        // updateComponentStyle 内部会更新 currentMaxZIndex
    };

    const sendToBack = (id: string) => {
        console.log(`[Store SendToBack] Action called for ${id}`);
        recordHistory(); // ++ Record history at the beginning

        const component = findComponentById(canvasComponents.value, id);
        if (!component) {
            console.warn(`[Store SendToBack] Component ${id} not found.`);
            return;
        }

        // 1. 找到父级数组和当前索引
        let parentArray: CanvasComponent[] | null = null;
        let currentIndex = -1;

        const parentComponent = findParentComponent(canvasComponents.value, id);
        if (parentComponent) {
            // 是嵌套组件
            if (parentComponent.children) {
                parentArray = parentComponent.children;
                currentIndex = parentArray.findIndex(c => c.id === id);
            } else {
                console.warn(`[Store SendToBack] Parent ${parentComponent.id} found but has no children array!`);
                return;
            }
        } else {
            // 是根组件
            parentArray = canvasComponents.value;
            currentIndex = parentArray.findIndex(c => c.id === id);
        }

        if (!parentArray || currentIndex === -1) {
            console.warn(`[Store SendToBack] Could not find component ${id} in its parent array.`);
            return;
        }

        // 2. 从数组中移除
        const [removedComponent] = parentArray.splice(currentIndex, 1);
        console.log(`[Store SendToBack] Removed ${id} from index ${currentIndex} in parent ${parentComponent?.id || 'root'}.`);

        // 3. 添加到数组开头
        parentArray.unshift(removedComponent);
        console.log(`[Store SendToBack] Added ${id} to the beginning of parent ${parentComponent?.id || 'root'}.`);

        // 4. 设置 zIndex 为 0
        const newZIndex = 0;
        console.log(`[Store SendToBack] Setting zIndex for ${id} to: ${newZIndex}`);
        // 直接修改移除后重新添加的组件对象的 style
        if (!removedComponent.style) { removedComponent.style = {}; }
        removedComponent.style.zIndex = newZIndex;
        // updateComponentStyle(id, { zIndex: newZIndex }); // 不再需要单独调用 updateStyle，因为我们直接修改了对象，并且 recordHistory 已在开头调用

        // TODO: Consider recalculating maxZIndex if needed, though setting to 0 shouldn't affect max.
    };

    // --- 撤销/重做 Actions ---
    const undo = () => {
        if (!canUndo.value) return;
        isRestoringState.value = true;
        redoStack.value.push(cloneDeep(canvasComponents.value));
        const prevState = undoStack.value.pop();
        if (prevState) {
            canvasComponents.value = cloneDeep(prevState);
            selectedComponentId.value = null;
        }
        // 延迟重置标志位，确保 Vue 更新完成
        nextTick(() => { isRestoringState.value = false; });
    };

    const redo = () => {
        if (!canRedo.value) return;
        isRestoringState.value = true;
        undoStack.value.push(cloneDeep(canvasComponents.value));
        const nextState = redoStack.value.pop();
        if (nextState) {
            canvasComponents.value = cloneDeep(nextState);
            selectedComponentId.value = null;
        }
        nextTick(() => { isRestoringState.value = false; });
    };

    // TODO: Add actions for history (undo/redo)

    // ++ Add Actions for Option Management ++
    const addOptionToGroup = (groupId: string, optionType: 'el-radio' | 'el-checkbox') => {
        recordHistory(); // Call internal history recorder
        const groupComponent = findComponentById(canvasComponents.value, groupId);
        if (groupComponent && (groupComponent.type === 'el-radio-group' || groupComponent.type === 'el-checkbox-group')) {
            if (!groupComponent.children) {
                groupComponent.children = [];
            }
            const newOptionId = `${optionType}-${uuidv4().substring(0, 8)}`;
            const newOptionIndex = (groupComponent.children?.length || 0) + 1;
            const newOption: CanvasComponent = {
                id: newOptionId,
                type: optionType,
                props: {
                    label: `option${newOptionIndex}`,
                    textContent: `选项${newOptionIndex}`,
                },
                style: { position: 'relative' },
            };
            groupComponent.children.push(newOption);
            console.log(`[Store Options] Added ${optionType} (${newOptionId}) to group ${groupId}`);
        } else {
            console.warn(`[Store Options] Could not add option: Group component ${groupId} not found or is not a group type.`);
        }
    };

    const removeOptionFromGroup = (groupId: string, optionId: string) => {
        recordHistory(); 
        const groupComponent = findComponentById(canvasComponents.value, groupId);
        if (groupComponent?.children) {
            const optionIndex = groupComponent.children.findIndex(opt => opt.id === optionId);
            if (optionIndex !== -1) {
                groupComponent.children.splice(optionIndex, 1);
                console.log(`[Store Options] Removed option ${optionId} from group ${groupId}`);
            } else {
                console.warn(`[Store Options] Could not remove option: Option ${optionId} not found in group ${groupId}`);
            }
        } else {
            console.warn(`[Store Options] Could not remove option: Group component ${groupId} not found or has no children.`);
        }
    };

    const updateOptionInGroup = (groupId: string, optionId: string, newProps: { label?: string; textContent?: string }) => {
        recordHistory(); 
        const groupComponent = findComponentById(canvasComponents.value, groupId);
        const optionComponent = groupComponent?.children?.find(opt => opt.id === optionId);
        if (optionComponent) {
            if (!optionComponent.props) {
                optionComponent.props = {};
            }
            let updated = false;
            if (newProps.label !== undefined && optionComponent.props.label !== newProps.label) {
                optionComponent.props.label = newProps.label;
                updated = true;
            }
            if (newProps.textContent !== undefined && optionComponent.props.textContent !== newProps.textContent) {
                optionComponent.props.textContent = newProps.textContent;
                updated = true;
            }
            if (updated) {
                 console.log(`[Store Options] Updated option ${optionId} in group ${groupId} with props:`, newProps);
            } else {
                 console.log(`[Store Options] No changes applied to option ${optionId} in group ${groupId}`);
            }
        } else {
            console.warn(`[Store Options] Could not update option: Option ${optionId} not found in group ${groupId}`);
        }
    };
    // ++ End Actions for Option Management ++

    // 添加 isDescendantOf 方法用于检查祖先关系
    const isDescendantOf = (components: CanvasComponent[], descendantId: string, ancestorId: string): boolean => {
        const descendant = findComponentById(components, descendantId);
        if (!descendant) return false;
        
        let current = descendant;
        let parent = findParentComponent(components, current.id);
        
        while (parent) {
            if (parent.id === ancestorId) {
                return true;
            }
            current = parent;
            parent = findParentComponent(components, current.id);
        }
        
        return false;
    };

    const moveComponent = (componentId: string, newParentId: string | null, newStyle: Partial<CSSProperties>, forceUpdate: boolean = true) => {
        recordHistory();
        
        const componentToMove = findComponentById(canvasComponents.value, componentId);
        if (!componentToMove) {
            console.error(`[Store] moveComponent: Component with ID ${componentId} not found.`);
            redoStack.value = [];
            undoStack.value.pop();
            return;
        }

        // 排除对容器本身或者不支持子组件的容器的非法拖放
        if (newParentId === componentId) {
            console.error(`[Store] moveComponent: Cannot move component into itself. ComponentId=${componentId}, newParentId=${newParentId}`);
            redoStack.value = [];
            undoStack.value.pop();
            return;
        }

        // 如果新父容器是当前组件的子容器，这是不允许的
        if (newParentId && isDescendantOf(canvasComponents.value, newParentId, componentId)) {
            console.error(`[Store] moveComponent: Cannot move a component to its descendant. ComponentId=${componentId}, newParentId=${newParentId}`);
            redoStack.value = [];
            undoStack.value.pop();
            return;
        }

        // 1. 查找要移动的组件当前的父组件
        let oldParent: CanvasComponent | null = null;
        let oldParentArray: CanvasComponent[] | null = null;
        let oldIndex = -1;

        // 尝试在根节点查找
        oldIndex = canvasComponents.value.findIndex(c => c.id === componentId);
        if (oldIndex !== -1) {
            oldParentArray = canvasComponents.value;
            oldParent = null; // 根节点没有父组件
        } else {
            // 如果不在根节点，递归查找
            const findRecursively = (components: CanvasComponent[], targetId: string): { parent: CanvasComponent, parentArr: CanvasComponent[], index: number } | null => {
                for (const comp of components) {
                    if (comp.children) {
                        const index = comp.children.findIndex(c => c.id === targetId);
                        if (index !== -1) {
                            return {
                                parent: comp,
                                parentArr: comp.children,
                                index: index
                            };
                        }
                        const found = findRecursively(comp.children, targetId);
                        if (found) return found;
                    }
                }
                return null;
            };
            const foundResult = findRecursively(canvasComponents.value, componentId);
            if (foundResult) {
                oldParent = foundResult.parent;
                oldParentArray = foundResult.parentArr;
                oldIndex = foundResult.index;
            }
        }

        if (!oldParentArray || oldIndex === -1) {
            console.error(`[Store moveComponent] Component ${componentId} not found.`);
            redoStack.value = []; // 操作失败，之前的 recordHistory 无效，清空 redo
            undoStack.value.pop(); // 移除无效的历史记录
            return;
        }

        // Save children reference before removing from old parent
        const childComponents = componentToMove.children || [];

        // 2. 从旧的位置移除
        oldParentArray.splice(oldIndex, 1);
        console.log(`[Store moveComponent] Removed ${componentId} from old parent ${oldParent?.id ?? 'root'}.`);

        // 3. 查找新的父组件
        let newParent: CanvasComponent | null = null;
        let newParentArray: CanvasComponent[] | null = null;
        if (newParentId) {
            newParent = findComponentById(canvasComponents.value, newParentId);
            if (newParent) {
                if (!newParent.children) {
                    newParent.children = [];
                }
                newParentArray = newParent.children;
            } else {
                console.error(`[Store moveComponent] New parent ${newParentId} not found. Aborting move.`);
                redoStack.value = []; 
                undoStack.value.pop();
                return;
            }
        } else {
            newParentArray = canvasComponents.value;
        }

        // 4. 更新组件样式和位置
        if (!componentToMove.style) componentToMove.style = {};

        if (newParent) { // 移动到容器内
            // 确保新父容器有定位上下文
            if (!newParent.style) newParent.style = {};
            if (!newParent.style.position) {
                newParent.style.position = 'relative';
                console.log(`[Store moveComponent] Set new parent ${newParent.id} position to relative.`);
            }

            // **直接应用传入的 newStyle 作为相对位置**
            Object.assign(componentToMove.style, newStyle);
            componentToMove.style.position = 'absolute';
            console.log(`[Store moveComponent] Moved ${componentId} into ${newParent.id}. Applied relative style:`, cloneDeep(newStyle));

        } else { // 移动到根画布 (保持不变，需要绝对定位)
            Object.assign(componentToMove.style, newStyle);
            componentToMove.style.position = 'absolute';
            console.log(`[Store moveComponent] Moved ${componentId} to root. Applied absolute style:`, cloneDeep(newStyle));
        }

        // 5. 添加到新的位置
        if (newParentArray) {
            newParentArray.push(componentToMove);
            console.log(`[Store moveComponent] Added ${componentId} to new parent ${newParent?.id ?? 'root'}. Final Style:`, cloneDeep(componentToMove.style)); // ++ Log Final Style
        } else {
            // 这理论上不应该发生，因为 newParentArray 在前面已确保存在
            console.error(`[Store moveComponent] Logic error: newParentArray is null!`);
            redoStack.value = []; // 操作失败
            undoStack.value.pop();
            return;
        }

        // 6. 强制更新：遍历子组件并应用当前相对样式，确保它们正确跟随父容器
        if (forceUpdate && childComponents.length > 0) {
            console.log(`[Store moveComponent] Force updating styles for ${childComponents.length} children of component ${componentId}`);
            
            // 递归确保所有子孙组件的样式保持同步
            const updateChildrenStyles = (children: CanvasComponent[]) => {
                for (const child of children) {
                    if (!child.style) child.style = {}; // 确保存在样式对象
                    
                    // 强制触发子组件的样式更新，确保相对定位正确
                    if (child.style.position !== 'absolute') {
                        child.style.position = 'absolute';
                    }
                    
                    // 创建一个新的样式对象，包含必要的定位属性
                    const updatedStyle = {
                        position: 'absolute',
                        left: child.style.left || '0px',
                        top: child.style.top || '0px',
                    };
                    
                    // 对子组件应用样式更新，强制重新渲染
                    Object.assign(child.style, updatedStyle);
                    console.log(`[Store moveComponent] Reapplied style for child ${child.id}:`, updatedStyle);
                    
                    // 递归处理所有子孙组件
                    if (child.children && child.children.length > 0) {
                        updateChildrenStyles(child.children);
                    }
                }
            };
            
            // 触发子组件样式更新
            updateChildrenStyles(childComponents);
        }

        console.log(`[Store moveComponent] Component ${componentId} moved successfully.`);
    };

    // ++ Re-add action to set dragging state ++
    const setDraggingState = (isDragging: boolean) => {
        isDraggingComponent.value = isDragging;
    };

    // 更新画布尺寸的 action
    const updateCanvasSize = (size: { width: number; height: number }) => {
        canvasSize.value = { ...size };
        console.log(`[Store] 画布尺寸已更新为: ${size.width}x${size.height}`);
    };

    // --- 新增：复制组件 ---
    const copyComponent = (id: string) => {
        const component = findComponentById(canvasComponents.value, id);
        if (!component) return;
        
        // 深拷贝组件，以确保不会修改原组件
        clipboardComponent.value = cloneDeep(component);
        console.log('[Store copyComponent] 已复制组件到剪贴板:', id);
    };

    // --- 新增：粘贴组件 ---
    const pasteComponent = (offsetX = 20, offsetY = 20) => {
        if (!clipboardComponent.value) {
            console.warn('[Store pasteComponent] 剪贴板为空，无法粘贴');
            return;
        }

        recordHistory();
        
        // 创建组件副本，为所有组件和子组件生成新的ID
        const generateNewIds = (component: CanvasComponent): CanvasComponent => {
            const newComponent = cloneDeep(component);
            // 生成新ID，保留原始类型前缀
            const idParts = component.id.split('-');
            const typePrefix = idParts[0];
            newComponent.id = `${typePrefix}-${uuidv4().substring(0, 8)}`;
            
            // 如果粘贴的是根级组件，则调整位置
            if (!component.style.position || component.style.position === 'absolute') {
                // 确保style对象存在
                if (!newComponent.style) newComponent.style = {};
                
                // 获取原始位置并添加偏移
                const originalLeft = parseInt(String(component.style.left), 10) || 0;
                const originalTop = parseInt(String(component.style.top), 10) || 0;
                
                // 设置新位置
                newComponent.style.left = `${originalLeft + offsetX}px`;
                newComponent.style.top = `${originalTop + offsetY}px`;
            }
            
            // 递归处理子组件
            if (newComponent.children && newComponent.children.length > 0) {
                newComponent.children = newComponent.children.map(child => generateNewIds(child));
            }
            
            return newComponent;
        };
        
        // 创建新组件并设置新ID
        const newComponent = generateNewIds(clipboardComponent.value);
        
        // 将新组件添加到画布
        canvasComponents.value.push(newComponent);
        
        // 选中新组件
        selectComponent(newComponent.id);
        
        // 更新最大z-index
        findAndUpdateMaxZIndex(canvasComponents.value);
        
        console.log('[Store pasteComponent] 已粘贴组件:', newComponent.id);
    };

    return {
        // State
        canvasComponents,
        selectedComponentId,
        undoStack,
        redoStack,
        currentMaxZIndex,
        gridSize,
        isDraggingComponent,
        canvasSize,
        clipboardComponent, // 新增：导出剪贴板状态

        // Getters
        selectedComponent,
        allComponentsFlatList,
        canUndo,
        canRedo,

        // Actions
        addComponent,
        selectComponent,
        deleteComponent,
        updateComponentStyle,
        updateComponentProps,
        updateComponentRootProps,
        bringToFront,
        sendToBack,
        undo,
        redo,
        addOptionToGroup,
        removeOptionFromGroup,
        updateOptionInGroup,
        moveComponent,
        setDraggingState,
        updateCanvasSize,
        copyComponent, // 新增：导出复制组件方法
        pasteComponent, // 新增：导出粘贴组件方法

        // 辅助函数
        findComponentById, // 重新导出辅助函数
        findParentComponent, // 重新导出辅助函数
    };
}, {
    // Pinia Store options can go here if needed
});

// Helper function (remains the same)
// **确保导出此函数**
export function isContainerType(type: string): boolean {
    return ['div', 'el-row', 'el-radio-group', 'el-checkbox-group'].includes(type);
}

// **需要添加 parsePx 辅助函数**
const parsePx = (value: string | undefined | number): number => {
    if (typeof value === 'number') return value;
    if (typeof value === 'string' && value.endsWith('px')) {
      const parsed = parseFloat(value.slice(0, -2));
      return isNaN(parsed) ? 0 : parsed;
    }
    // 如果没有 'px' 后缀，尝试直接解析
    if (typeof value === 'string') {
        const parsed = parseFloat(value);
        return isNaN(parsed) ? 0 : parsed;
    }
    return 0; 
  };

// --- 不再需要 $onAction --- 